import { corsHeaders } from '../utils/cors'
import { UserModel } from '../models/user'
import { Logger } from '../utils/logger'
import { generateRandomKey, encrypt, decrypt } from '../utils/crypto'
import { sign } from '@tsndr/cloudflare-worker-jwt'
import { kvHelper } from '../utils/kv-helper'

export const authHandler = {
  // 获取登录challenge
  async getChallenge(request, env) {
    const logger = new Logger(env).setModule('Auth:getChallenge');
    try {
      const { email } = await request.json();
      logger.debug('获取登录challenge', { email });

      // 生成随机challenge
      const challenge = crypto.randomUUID();
      
      // 查询用户是否存在
      const user = await UserModel.findByEmail(env, email);
      
      // 生成两个salt，一个用于认证，一个用于加密
      const authSalt = user ? user.auth_salt : crypto.randomUUID();
      const encryptSalt = user ? user.encrypt_salt : crypto.randomUUID();
      
      // 保存challenge到KV
      await kvHelper.setLoginChallenge(env, email, challenge);
      
      // 如果是新用户，保存salt到KV
      if (!user) {
        await Promise.all([
          kvHelper.setLoginAuthSalt(env, email, authSalt),
          kvHelper.setLoginEncryptSalt(env, email, encryptSalt)
        ]);
      }

      return new Response(JSON.stringify({ 
        authSalt,
        encryptSalt,
        challenge 
      }), {
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    } catch (error) {
      logger.error('获取登录challenge失败', error);
      return new Response(JSON.stringify({ 
        error: '获取登录challenge失败',
        message: env.DEBUG === 'true' ? error.message : undefined
      }), {
        status: 500,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    }
  },

  // 验证登录
  async login(request, env) {
    const logger = new Logger(env).setModule('Auth:login');
    try {
      const { email, encryptedChallenge, iv, authKey, encryptKey } = await request.json();
      logger.debug('验证登录', { email, encryptedChallenge, iv });
      //增加参数校验
      if (!email || !encryptedChallenge || !iv || !encryptKey) {
        logger.warn('参数不完整', { email, encryptedChallenge, iv, authKey, encryptKey });
        return new Response(JSON.stringify({ error: '参数不完整' }), {
          status: 400,
          headers: { ...corsHeaders, 'Content-Type': 'application/json' }
        });
      }

      // 获取之前保存的challenge
      const storedChallenge = await kvHelper.getLoginChallenge(env, email);
      
      // 查询用户是否存在
      const user = await UserModel.findByEmail(env, email);
      logger.debug('查询用户结果', { exists: !!user });

      // 获取salt（已存在用户使用数据库中的salt，新用户从KV获取）
      const authSalt = user ? user.auth_salt : await kvHelper.getLoginAuthSalt(env, email);
      const encryptSalt = user ? user.encrypt_salt : await kvHelper.getLoginEncryptSalt(env, email);

      if (!storedChallenge || (!user && (!authSalt || !encryptSalt))) {
        logger.warn('Challenge或Salt不存在或已过期', { email });
        return new Response(JSON.stringify({ error: 'Challenge或Salt不存在或已过期' }), {
          status: 401,
          headers: { ...corsHeaders, 'Content-Type': 'application/json' }
        });
      }

      if (!user) {
        // 用户不存在,创建新用户
        logger.info('用户不存在,开始创建新用户', { email });
        
        // 验证challenge
        try {
          const decryptedChallenge = await decrypt(encryptedChallenge, iv, authKey);
          logger.debug('解密结果', { decryptedChallenge, storedChallenge });
          if (decryptedChallenge !== storedChallenge) {
            throw new Error('Challenge验证失败');
          }
        } catch (error) {
          logger.error('Challenge验证失败', error);
          return new Response(JSON.stringify({ error: 'Challenge验证失败' }), {
            status: 401,
            headers: { ...corsHeaders, 'Content-Type': 'application/json' }
          });
        }

        // 生成主密钥明文
        const masterKey = await generateRandomKey();
        // 用加密密钥对主密钥加密
        const { encrypted: encryptedMasterKey, iv: masterKeyIv } = await encrypt(masterKey, encryptKey);

        // 保存新用户
        const newUser = await UserModel.create(env, {
          email,
          authKey,  // 保存认证密钥
          authSalt, // 保存认证salt
          encryptSalt,  // 保存加密salt
          masterKey: encryptedMasterKey,
          masterKeyIv: masterKeyIv
        });

        // 生成JWT token
        const token = await sign({ 
          email,
          userId: newUser.id
        }, env.JWT_SECRET);
        
        // 保存主密钥到KV，设置1小时过期
        await kvHelper.setMasterKey(env, email, masterKey, 3600*8);
        
        // 删除使用过的challenge和salt
        await Promise.all([
          kvHelper.deleteLoginChallenge(env, email),
          kvHelper.deleteLoginAuthSalt(env, email),
          kvHelper.deleteLoginEncryptSalt(env, email)
        ]);

        return new Response(JSON.stringify({
          token
        }), {
          headers: { ...corsHeaders, 'Content-Type': 'application/json' }
        });
      } else {
        // 用户存在，验证challenge
        try {
          const decryptedChallenge = await decrypt(encryptedChallenge, iv, user.auth_key);
          logger.debug('解密结果', { decryptedChallenge, storedChallenge });
          if (decryptedChallenge !== storedChallenge) {
            throw new Error('Challenge验证失败');
          }
        } catch (error) {
          logger.warn('密码错误', { email });
          return new Response(JSON.stringify({ error: '密码错误' }), {
            status: 401,
            headers: { ...corsHeaders, 'Content-Type': 'application/json' }
          });
        }

        // 使用加密密钥解密主密钥
        const masterKey = await decrypt(user.master_key, user.master_key_iv, encryptKey);
        await kvHelper.setMasterKey(env, email, masterKey, 3600*8);
        logger.info('用户存在,生成新token');
        const token = await sign({ 
          email,
          userId: user.id
        }, env.JWT_SECRET);
        
        // 删除使用过的challenge和salt
        await Promise.all([
          kvHelper.deleteLoginChallenge(env, email),
          kvHelper.deleteLoginAuthSalt(env, email),
          kvHelper.deleteLoginEncryptSalt(env, email)
        ]);

        return new Response(JSON.stringify({
          token
        }), {
          headers: { ...corsHeaders, 'Content-Type': 'application/json' }
        });
      }
    } catch (error) {
      logger.error('登录失败', error);
      return new Response(JSON.stringify({ 
        error: '登录失败',
        message: env.DEBUG === 'true' ? error.message : undefined
      }), {
        status: 500,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    }
  },

  // 忘记密码处理
  async forgotPassword(request, env) {
    const logger = new Logger(env).setModule('Auth:forgotPassword');
    try {
      const { email } = await request.json();
      logger.debug('处理忘记密码请求', { email });
      
      // 检查用户是否存在
      const user = await UserModel.findByEmail(env, email);
      if (!user) {
        logger.warn('用户不存在', { email });
        return new Response(JSON.stringify({ error: '用户不存在' }), {
          status: 404,
          headers: { ...corsHeaders, 'Content-Type': 'application/json' }
        });
      }

      // TODO: 发送重置密码邮件
      logger.info('用户存在,准备发送重置密码邮件', { email });

      return new Response(JSON.stringify({ message: '重置密码链接已发送' }), {
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    } catch (error) {
      logger.error('处理忘记密码请求失败', error);
      return new Response(JSON.stringify({ 
        error: '发送重置密码邮件失败',
        message: env.DEBUG === 'true' ? error.message : undefined
      }), {
        status: 500,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    }
  },

  // 在 authHandler 对象中添加新方法
  async getEncryptSalt(request, env) {
    const logger = new Logger(env).setModule('Auth:getEncryptSalt');
    try {
      const { email } = request.user;
      logger.debug('获取加密salt', { email });

      // 生成随机salt
      const salt = crypto.randomUUID();
      // 保存salt到KV,10分钟过期
      const key = `encrypt_salt:${email}`;
      await env.MIMI_KV.put(key, salt, { expirationTtl: 600 });

      return new Response(JSON.stringify({ salt }), {
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    } catch (error) {
      logger.error('获取加密salt失败', error);
      return new Response(JSON.stringify({
        error: '获取加密salt失败',
        message: env.DEBUG === 'true' ? error.message : undefined
      }), {
        status: 500,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    }
  },

  // 检查用户是否存在
  async checkUser(request, env) {
    const logger = new Logger(env).setModule('Auth:checkUser');
    try {
      const { email } = await request.json();
      logger.debug('检查用户是否存在', { email });

      const user = await UserModel.findByEmail(env, email);
      logger.debug('查询用户结果', { exists: !!user });

      return new Response(JSON.stringify({ 
        exists: !!user 
      }), {
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    } catch (error) {
      logger.error('检查用户失败', error);
      return new Response(JSON.stringify({ 
        error: '检查用户失败',
        message: env.DEBUG === 'true' ? error.message : undefined
      }), {
        status: 500,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    }
  },

  // 登出
  async logout(request, env) {
    const logger = new Logger(env).setModule('Auth:logout');
    try {
      const { email } = request.user;
      
      // 删除KV中的主密钥
      await kvHelper.deleteMasterKey(env, email);

      return new Response(JSON.stringify({ 
        message: '登出成功'
      }), {
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    } catch (error) {
      logger.error('登出失败', error);
      return new Response(JSON.stringify({ 
        error: '登出失败',
        message: env.DEBUG === 'true' ? error.message : undefined
      }), {
        status: 500,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    }
  }
}; 